<?php

namespace App\Http\Services;

use App\Http\Model\MonitoringLink\AccessToken;
use App\Http\Model\System;
use App\Http\Model\UserRegisterLog;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

/**
 * Apple ASA自归因业务
 *
 * Created on 2021/12/2 13:49
 * @Author <yuxiang.zhu@asiainnovations.net>
 */
class AppleAsaReportServices extends CommonServices
{
    /**
     * Apple ASA自归因业务
     *
     * Created at 2021/12/2 13:52
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param string $token
     * @param string $idfa
     */
    public function dealAsaReport(string $token, string $idfa)
    {
        $token = trim($token);
        if (!$token) {
            return;
        }

        $paras = [
            'iad-org-id' => '',
            'iad-attribution' => 'false',
        ];
        $record = ['code' => 1, 'idfa' => $idfa, 'paras' => json_encode([$paras])];
        // step1:根据token获取attribution数据，token有效期24小时
        $requestUrl = 'https://api-adservices.apple.com/api/v1/';
        $requestResult = curl_request($requestUrl, $token, 'plain');
        $systemService = new SystemServices();
        if (strpos($requestResult, 'attribution') === false) {//请求失败了, 返回了400(token无效)/404(未找到归因记录)/500(服务器暂时关闭或无法访问)
            $systemService->postAsaReport($record);
            return;
        }

        $requestResultDecode = json_decode($requestResult, true);
        $orgId = $requestResultDecode['orgId'];
        $campaignId = $requestResultDecode['campaignId'];//广告系列id
        $adGroupId = $requestResultDecode['adGroupId'];//广告组id
        $keywordId = intval($requestResultDecode['keywordId']);//关键词id
        $clickDate = $requestResultDecode['clickDate'] ?? '';//用户最近一次点击广告的时间
        $countryOrRegion = $requestResultDecode['countryOrRegion'] ?? '';//国家或地区
        $conversionType = $requestResultDecode['conversionType'] ?? '';//下载类型

        /*
        //方便测试
        $campaignId = 939205986;//广告系列id
        $adGroupId = 939459465;//广告组id
        $keywordId = 939467287;//关键词id
        */


        $record['code'] = 0;//表示成功
        $paras = [
            'iad-keyword' => '',
            'iad-purchase-date' => '',
            'iad-adgroup-id' => $adGroupId,
            'iad-campaign-id' => $campaignId,
            'iad-lineitem-id' => '',
            'iad-conversion-date' => '',
            'iad-org-id' => $orgId,
            'iad-keyword-id' => $keywordId,
            'iad-conversion-type' => $conversionType,
            'iad-country-or-region' => $countryOrRegion,
            'iad-org-name' => '',
            'iad-campaign-name' => '',
            'iad-click-date' => $clickDate,
            'iad-attribution' => $keywordId ? 'true' : 'false',
            'iad-adgroup-name' => '',
            'iad-keyword-matchtype' => '',
            'iad-lineitem-name' => '',
        ];

        $this->dealPlatform(intval($orgId), $paras['iad-attribution']);// 执行第一次
        $accessToken = (new AccessToken())->getAppleASAAccessToken();
        if (!$accessToken) {
            $record['paras'] = json_encode([$paras]);
            $systemService->postAsaReport($record);
            return;
        }

        $requestUrl = 'https://api.searchads.apple.com/api/v4/campaigns/' . $campaignId
            . '/adgroups/' . $adGroupId . '/targetingkeywords/' . $keywordId;
        $headers = [
            'Authorization:Bearer ' . $accessToken,
            'X-AP-Context:orgId=' . $orgId,
        ];
        $requestResult = curl_request($requestUrl, [], 'urlencoded', 'GET', $headers);// 根据关键词id获取关键词信息
        if (!$requestResult) {
            $record['paras'] = json_encode([$paras]);
            $systemService->postAsaReport($record);
            return;
        }

        $requestResultDecode = json_decode($requestResult, true);
        if (!$requestResultDecode['data']) {
            $record['paras'] = json_encode([$paras]);
            $systemService->postAsaReport($record);
            return;
        }

        $data = $requestResultDecode['data'];
        $paras = array_merge($paras, [
            'iad-keyword' => $data['text'] ?? '',
            'iad-lineitem-id' => $data['id'],
            'iad-keyword-matchtype' => $data['matchType'] ?? '',
        ]);
        $record['paras'] = json_encode([$paras]);
        $systemService->postAsaReport($record);
        $this->dealPlatform(intval($orgId), $paras['iad-attribution']);// 执行第二次
    }

    /**
     * Created at 2021/12/27 11:46
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $orgId
     * @param string $attribution
     */
    private function dealPlatform(int $orgId, string $attribution)
    {
        $data = $this->parse_app_UA();
        // 苹果渠道推广
        if ('3001' == $data['channel_id'] && $orgId && $attribution == 'true') {
            $platform = $orgId == 3170040 ? 'asa_haoxin' : 'asa_report';
            $model = new UserRegisterLog();
            if ($this->currentUserId > 0) {
//                $userRegisterLog = ['user_id' => $this->currentUserId];
                $userRegisterLog = $model->getUserRegisterLog($this->currentUserId);
                $userRegisterLog = (Array)($userRegisterLog);
            } else {
                $guid = $data['guid'] ?? '';
                $userRegisterLog = $guid ? $model->findRecordByGuid($guid, ['user_id']) : [];
            }

            if ($userRegisterLog
                && (!isset($userRegisterLog['platform']) || empty($userRegisterLog['platform']) || $userRegisterLog['platform'] == '3001')) {
                $model->updatePlatform($userRegisterLog['user_id'], $platform);
            }
        }
    }
}